<script setup>
import { ref } from 'vue'
import { ElForm, ElFormItem, ElInput, 
    ElButton, ElCard, ElRow, ElCol ,
    ElMessage, ElUpload
    } from 'element-plus'
import { userRegisterService } from '@/api/user.js'
import { generateCaptcha, refreshCaptcha } from '@/utils/captcha.js'
//路由
import { useRouter } from 'vue-router'

const router = useRouter()

// 表单数据
const formData = ref({
  username: '',
  password: '',
  confirmPassword: '',
  captcha: '',
  avatar: '' // 添加头像字段
});

// 表单验证规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value.length < 2) {
          callback(new Error('用户名长度不能少于2位'));
        } 
         else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value.length < 5) {
          callback(new Error('密码长度不能少于5位'));
        } else if (!/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]+$/.test(value)) {
          callback(new Error('密码必须包含字母和数字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== formData.value.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur'},
    { 
      validator: (rule, value, callback) => {
        if (value.length !== 4) {
          callback(new Error('验证码长度必须为4位'));
        } else if (value.toUpperCase() !== currentCaptcha.value.code) {
          callback(new Error('验证码不正确'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 表单引用
const formRef = ref();

// 图形验证码相关
const currentCaptcha = ref(generateCaptcha());
const captchaUrl = ref(currentCaptcha.value.imageUrl);

// 头像上传相关
const avatarUrl = ref('');

// 刷新验证码
const refreshCaptchaHandler = () => {
  refreshCaptcha((data) => {
    currentCaptcha.value = data;
    captchaUrl.value = data.imageUrl;
  })
};

// 头像上传处理
const handleAvatarSuccess = (response, uploadFile) => {
  // 检查响应是否成功
  if (response.code === 0) {
    avatarUrl.value = URL.createObjectURL(uploadFile.raw);
    formData.value.avatar = response.data; // 使用后端返回的图片URL
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error(response.message || '头像上传失败');
  }
};

// 添加上传前确认提示
const beforeAvatarUpload = (rawFile) => {
  // 添加确认提示
  const confirmed = window.confirm('确定要上传这张图片作为头像吗？');
  if (!confirmed) {
    return false;
  }
  
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('头像必须是 JPG 或 PNG 格式!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 表单提交
const handleRegister = async () => {
  try {
    // 确保头像URL被包含在提交的数据中
    const registerData = {
      ...formData.value,
      avatar: avatarUrl.value || 'https://campus-services-yu.oss-cn-shenzhen.aliyuncs.com/f30310e7-0035-42c9-9d0e-799d8250ce72.jpg'
    };
    
    await userRegisterService(registerData);
    ElMessage.success('注册成功');
    // 注册成功后跳转到登录页面
    router.push('/login');
  } catch (error) {
    // 检查是否是HTTP错误响应
    if (error.response && error.response.data) {
      ElMessage.error(error.response.data.message || '注册失败');
    } else {
      // 其他类型的错误
      ElMessage.error(error.message || '注册失败，请稍后重试');
    }
    return;
  }
};
</script>

<template>
  <el-row class="login-page">
    <!-- 左侧背景图片 -->
    <el-col :span="12" class="bg"></el-col>
    
    <!-- 右侧表单区域 -->
    <el-col :span="12" class="form-col">
      <div class="form-container">
        <div class="register-header">
          <h1 class="platform-name">
            <span class="app-name">校园信息平台</span>
          </h1>
          <p class="platform-desc">注册新账号</p>
        </div>
        
        <el-card class="register-card">
          <h2 class="register-title">注册账号</h2>
          
          <el-form 
            ref="formRef"
            :model="formData" 
            :rules="rules" 
            label-width="80px" 
            class="register-form"
          >
            <!-- 添加头像上传区域 -->
            <div class="avatar-section">
              <div class="avatar-container">
                <div class="avatar-wrapper">
                  <img 
                    v-if="avatarUrl" 
                    :src="avatarUrl" 
                    class="avatar-preview" 
                    alt="用户头像"
                  />
                  <img 
                    v-else 
                    src="https://campus-services-yu.oss-cn-shenzhen.aliyuncs.com/f30310e7-0035-42c9-9d0e-799d8250ce72.jpg" 
                    class="avatar-preview" 
                    alt="默认头像"
                  />
                </div>
              </div>
              <el-upload
                class="avatar-uploader"
                action="/api/register/avatar"
                name="file"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                :before-upload="beforeAvatarUpload"
                :with-credentials="false"
                :headers="{ skipAuth: true }"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </div>
            
            <el-form-item label="用户名" prop="username">
              <el-input v-model="formData.username" placeholder="请输入用户名" />
            </el-form-item>
            
            <el-form-item label="密码" prop="password">
              <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="formData.confirmPassword" type="password" placeholder="请确认密码" show-password />
            </el-form-item>
            
            <el-form-item label="验证码" prop="captcha">
              <div class="captcha-container">
                <el-input 
                  v-model="formData.captcha" 
                  placeholder="请输入验证码" 
                  class="captcha-input"
                  maxlength="4"
                />
                <img 
                  :src="captchaUrl" 
                  class="captcha-image" 
                  @click="refreshCaptchaHandler"
                  alt="验证码"
                />
              </div>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="handleRegister" class="register-btn">注册</el-button>
            </el-form-item>
          </el-form>
          
          <div class="login-link">
            <a href="/login">已有账号？立即登录</a>
          </div>
        </el-card>
      </div>
    </el-col>
  </el-row>
</template>

<style scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  margin: 0 !important;
}

.bg {
  background: url("@/assets/images/register.jpg") no-repeat center;
  background-size: cover;
  border-radius: 0 20px 20px 0;
  height: 100vh;
  background-color: #f5f5f5; /* 添加背景色以防图片加载失败 */
}

.form-col {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  padding: 0;
}

.form-container {
  width: 100%;
  max-width: 450px;
  padding: 0 20px;
}

.register-header {
  margin-bottom: 30px;
  text-align: center;
}

.platform-name {
  font-size: 28px;
  margin-bottom: 10px;
  color: #333;
}

.app-name {
  color: #409eff;
  font-weight: bold;
}

.platform-desc {
  font-size: 16px;
  color: #666;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.register-card {
  padding: 30px;
  border: none;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  background: linear-gradient(145deg, #ffffff, #f0f0f0);
}

.register-title {
  text-align: center;
  margin-bottom: 25px;
  font-size: 22px;
  color: #333;
  font-weight: 600;
}

.register-form {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #555;
}

:deep(.el-input__inner) {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  padding: 12px 15px;
  transition: border-color 0.3s;
}

:deep(.el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

:deep(.el-radio__label) {
  color: #666;
}

.register-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  border-radius: 8px;
  background: linear-gradient(90deg, #409eff, #1a73e8);
  border: none;
  transition: all 0.3s ease;
  font-weight: 500;
  letter-spacing: 1px;
}

.register-btn:hover {
  background: linear-gradient(90deg, #1a73e8, #409eff);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transform: translateY(-2px);
}

.login-link {
  text-align: center;
  margin-top: 20px;
}

.login-link a {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
  transition: all 0.3s;
}

.login-link a:hover {
  text-decoration: underline;
  color: #1a73e8;
}

/* 响应式设计 */


@media (max-width: 768px) {
  .login-page {
    flex-direction: column;
  }
  
  .bg {
    height: 200px;
    border-radius: 0;
    background-size: 120px auto, cover;
  }
  
  .form-col {
    height: auto;
    padding: 20px;
  }
  
  .form-container {
    padding: 0;
  }
  
  .register-card {
    padding: 20px;
  }
}

@media (max-width: 576px) {
  .register-header {
    margin-top: 20px;
  }
  
  .platform-name {
    font-size: 24px;
  }
  
  .register-card {
    padding: 15px;
  }
  
  .register-title {
    font-size: 20px;
  }
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  width: 120px;
  height: 40px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  object-fit: cover;
}

/* 添加头像相关样式 */
.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-container {
  margin-bottom: 15px;
}

.avatar-wrapper {
  position: relative;
  width: 100px;
  height: 100px;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.avatar-preview:hover {
  transform: scale(1.1);
}

.avatar-uploader {
  display: flex;
  justify-content: center;
}
</style>